<?php

declare(strict_types=1);

namespace App\Command;

use Hyperf\Command\Command as HyperfCommand;
use Hyperf\Command\Annotation\Command;
use Psr\Container\ContainerInterface;
use Service\CommodityService\CommodityStockSkillService;

/**
 * 处理redis扣减消息同步功能
 * @Command
 */
class OrderStockSubscribeMessage extends HyperfCommand
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;

        parent::__construct('OrderStockSubscribeMessage');
    }

    public function configure()
    {
        parent::configure();
        $this->setDescription('监控扣减库存微服务消息功能');
    }

    public function handle()
    {
        $redis = redis();
        $redis->setOption(\Redis::OPT_READ_TIMEOUT,"-1");
        $redis->subscribe([CommodityStockSkillService::redis_subscribe_queue], function($redis, $channel, $message) 
        {
            echo "Received message: {$message}\n";
            $messageArr = \explode("_",$message);
            if( count($messageArr) == 2 ) 
            {
                $sku_arr = \explode(":",$messageArr[0]);
                $skuCode = (string)$sku_arr[1];
                $number = (string)$messageArr[1];
                $result = CommodityStockSkillService::instance()->syncMysqlStockDecr($skuCode,$number);
                echo json_encode($result,JSON_UNESCAPED_UNICODE).PHP_EOL;
            }
        });
    }
}
